<script setup lang="ts">
import { ref, reactive } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { phoneRules } from "../utils/rule";
import type { FormInstance } from "element-plus";
import { useVerifyCode } from "../utils/verifyCode";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { useRouter } from "vue-router";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import type { PartialAuthData, LoginSuccessData } from "@/api/user";
import Iphone from "~icons/ep/iphone";
import Keyhole from "~icons/ri/shield-keyhole-line";

const router = useRouter();
const loading = ref(false);
const ruleForm = reactive({
  phone: "",
  verifyCode: ""
});
const ruleFormRef = ref<FormInstance>();
const { isDisabled, text, start, end } = useVerifyCode({
  scene: "login",
  resolvePhone: () => ruleForm.phone
});

const onLogin = async () => {
  if (!ruleFormRef.value) return;
  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid) return;
  loading.value = true;
  try {
    const userStore = useUserStoreHook();
    const res = await userStore.loginBySms({
      phone: ruleForm.phone,
      code: ruleForm.verifyCode
    });
    if (res.success && res.data) {
      const data = res.data as PartialAuthData | LoginSuccessData;
      if ((data as PartialAuthData).partial) {
        message("账号需完成后续流程，请按提示操作", { type: "warning" });
      } else {
        await initRouter();
        const top = getTopMenu(true).path;
        await router.push(top);
        message("登录成功", { type: "success" });
      }
    } else {
      message(res.msg || "登录失败", { type: "error" });
    }
  } catch (error: any) {
    message(error?.message ?? "登录失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

const handleSendCode = () => {
  start(ruleFormRef.value, "phone", 60);
};

const onBack = () => {
  end();
  useUserStoreHook().SET_CURRENTPAGE(0);
};
</script>

<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="phoneRules" size="large">
    <Motion>
      <el-form-item prop="phone">
        <el-input
          v-model="ruleForm.phone"
          clearable
          placeholder="请输入手机号"
          :prefix-icon="useRenderIcon(Iphone)"
        />
      </el-form-item>
    </Motion>

    <Motion :delay="100">
      <el-form-item prop="verifyCode">
        <div class="w-full flex justify-between">
          <el-input
            v-model="ruleForm.verifyCode"
            clearable
            placeholder="请输入短信验证码"
            :prefix-icon="useRenderIcon(Keyhole)"
          />
          <el-button
            :disabled="isDisabled"
            class="ml-2!"
            @click="handleSendCode"
          >
            {{ text.length > 0 ? `${text}s` : "获取验证码" }}
          </el-button>
        </div>
      </el-form-item>
    </Motion>

    <Motion :delay="150">
      <el-form-item>
        <el-button
          class="w-full"
          size="default"
          type="primary"
          :loading="loading"
          @click="onLogin"
        >
          验证码登录
        </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="200">
      <el-form-item>
        <el-button class="w-full" size="default" @click="onBack">
          返回
        </el-button>
      </el-form-item>
    </Motion>
  </el-form>
</template>
